package com.study.springsecurity.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * response工具类
 *
 * @Author YL
 * @Create 2024/4/3 17:38
 * @Version 1.0
 */
@Slf4j
public class ResponseUtil {

    public static void writeJsonUtf8(HttpServletResponse response, Object... contents) {
        writeJsonUtf8(response, HttpStatus.OK, contents);
    }

    public static void writeJsonUtf8(HttpServletResponse response, HttpStatus status, Object... contents) {
        response.setStatus(status.value());
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            String[] contentJsonArr = Arrays.stream(contents).map(JSON::toJSONString).collect(Collectors.toList()).toArray(new String[contents.length]);
            IoUtil.writeUtf8(response.getOutputStream(), true, contentJsonArr);
        } catch (IOException e) {
            log.error("ResponseUtil writeJsonUtf8 IOException", e);
        }
    }

}
